<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{
  public function init()
  {
    header('Content-Type:text/html;charset=utf-8');
    if (isset($_GET['id']) && $_GET['id'] <= 0) {
      $this->error('非法请求<br>参数ID必须大于0', 400);
    }
  }

  /**
   * @var string the default layout for the controller view. Defaults to '//layouts/column1',
   * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
   */
  public $layout = '//layouts/site';
  /**
   * @var array context menu items. This property will be assigned to {@link CMenu::items}.
   */
  public $menu = array();
  /**
   * @var array the breadcrumbs of the current page. The value of this property will
   * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
   * for more details on how to specify this property.
   */
  public $breadcrumbs = array();


  /**
   * 成功提示
   * @param string $msg
   * @param string $url
   */
  public function success($msg = '', $url = '')
  {
    if (empty($url)) {
      $url = 'javascript:history.back()';
    }
    $this->render('/site/success', array(
        'url' => $url,
        'msg' => $msg
    ));
    exit;
  }

  /**
   * 错误提示
   * @param string $msg
   * @param integer $code
   * @param string $url
   */
  public function error($msg = '', $code = 404, $url = '')
  {
    if (empty($url)) {
      $url = 'javascript:history.back()';
    }
    header("HTTP/1.1 $code");
    $this->render('/site/error2', array(
        'url' => $url,
        'msg' => $msg
    ));
    exit;
  }

  /**
   * 是否手机浏览器
   * @return bool
   */
  public function isMobile()
  {
    $array = array(
        'iphone',
        'android',
        'phone',
        'mobile',
        'wap',
        'netfront',
        'java',
        'opera mobi',
        'opera mini',
        'ucweb',
        'windows ce',
        'symbian',
        'series',
        'webos',
        'sony',
        'blackberry',
        'dopod',
        'nokia',
        'samsung',
        'palmsource',
        'xda',
        'pieplus',
        'meizu',
        'midp',
        'cldc',
        'motorola',
        'foma',
        'docomo',
        'up.browser',
        'up.link',
        'blazer',
        'helio',
        'hosin',
        'huawei',
        'novarra',
        'coolpad',
        'webos',
        'techfaith',
        'palmsource',
        'alcatel',
        'amoi',
        'ktouch',
        'nexian',
        'ericsson',
        'philips',
        'sagem',
        'wellcom',
        'bunjalloo',
        'maui',
        'smartphone',
        'iemobile',
        'spice',
        'bird',
        'zte-',
        'longcos',
        'pantech',
        'gionee',
        'portalmmm',
        'jig browser',
        'hiptop',
        'benq',
        'haier',
        '^lct',
        '320x320',
        '240x320',
        '176x220'
    );
    foreach($array as $row){
      if(strstr(strtolower(Yii::app()->request->userAgent),$row) != false){
        return true;
      }
    }
    return false;
  }

  /**
   * 检查游客
   * @return mixed
   */
  public function checkGuest()
  {
    if(Yii::app()->user->isGuest){
      $this->error('请登录!',200,Yii::app()->createUrl('site/login'));
    }
  }

  /**
   * 获取模型错误
   * @param array $error
   * @return mixed
   */
  public function getError($error = array())
  {
    $data = array();
    if (is_array($error)) {
      $i = 0;
      foreach ($error as $row) {
        if ($i == 0) {
          $data = $row;
        }
        $i++;
      }
    } else {
      $data[0] = $error;
    }
    return $data[0];
  }

  /**
   * 过滤
   * @param array $data
   * @return array
   */
  public function filter($data = array())
  {
    $data = is_array($data) ? $data : array();
    $data = array_map(function ($value) {
      return htmlspecialchars(trim($value));
    }, $data);
    return $data;
  }

  /**
   * 中文字符串截取
   * @param $str
   * @param int $start
   * @param $length
   * @param string $charset
   * @return string
   */
  public function cn_substr($str, $start = 0, $length, $charset = "utf-8")
  {
    if (function_exists("mb_substr")) {
      $slice = mb_substr($str, $start, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
      $slice = iconv_substr($str, $start, $length, $charset);
    } else {
      $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
      $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
      $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
      $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
      preg_match_all($re[$charset], $str, $match);
      $slice = join("", array_slice($match[0], $start, $length));
    }
    return $slice;
  }

  /**
   * js消息提示
   * @param string $msg
   * @param string $url
   */
  public function jsMsg($msg = '', $url = '')
  {
    echo empty($url) ? '<script>alert("' . $msg . '");history.back()</script>' : '<script>alert("' . $msg . '");window.location.href="' . $url . '";</script>';
    exit;
  }

  /**
   * 检测用户登录状态
   * @param int $type
   * @param bool $layouts
   * @return bool
   */
  public function checkUserLogin($type = 1, $layouts = true)
  {
    if (Yii::app()->user->isGuest) {
      $this->redirect(Yii::app()->createUrl('site/login'));
    } else if (Yii::app()->user->getState('type') != $type) {
      $this->redirect(Yii::app()->createUrl('site/login'));
    } else if (Yii::app()->user->getState('type') == $type) {
      if ($layouts) {
        if ($type == 1) {
          $this->layout = '//layouts/student';
        }
        if ($type == 2) {
          $this->layout = '//layouts/teacher';
        }
        if ($type == 3) {
          $this->layout = '//layouts/admin';
        }
      }
      return true;
    }
  }

  public function iCheck()
  {
    Yii::app()->clientScript->registerCssFile('/public/lib/icheck/skins/all.css');
    Yii::app()->clientScript->registerScriptFile('/public/lib/icheck/icheck.min.js', CClientScript::POS_BEGIN);
  }

  /**
   * 检查课程
   * @param int $lesson_id
   * @param int $user_id
   * @param bool $checkState
   * @param bool $js
   * @return bool
   */
  public function checkLesson($lesson_id = 0, $user_id = 0, $checkState = false, $js = true)
  {
    if ($lesson_id > 0) {
      $criteria = new CDbCriteria();
      $criteria->condition = 'lesson_id=:lesson_id';
      if ($checkState) {
        $criteria->addCondition('state=1');
      }
      if ($user_id > 0) {
        $criteria->addCondition('user_id=:user_id');
        $criteria->params = array(
            ':lesson_id' => $lesson_id,
            ':user_id' => $user_id
        );
      } else {
        $criteria->params = array(
            ':lesson_id' => $lesson_id
        );
      }

      $data = Lesson::model()->find($criteria);
      if (empty($data)) {
        if ($js) {
          $this->jsMsg('课程不存在!');
        } else {
          $this->error('课程不存在!',404);
        }
      } else {
        return true;
      }
    } else {
      if ($js) {
        $this->jsMsg('课程不存在!');
      } else {
        $this->error('课程不存在!',404);
      }
    }
  }

  /**
   * 检查文章
   * @param int $article_id
   * @param int $user_id
   * @param bool $js
   * @return bool
   */
  public function checkArticle($article_id = 0, $user_id = 0, $js = true)
  {
    if ($article_id > 0) {
      $criteria = new CDbCriteria();
      $criteria->condition = 'article_id=:article_id';
      $criteria->params = array(':article_id' => $article_id);
      if ($user_id > 0) {
        $criteria->with = array(
            'lesson'
        );
      }
      $data = Article::model()->with('lesson')->find($criteria);
      if (empty($data)) {
        if ($js) {
          $this->jsMsg('文章不存在!');
        } else {
          $this->error('文章不存在!',404);
        }
      } else if ($user_id > 0 && $data->lesson->user_id != $user_id) {
        if ($js) {
          $this->jsMsg('该文章所属课程不是你!');
        } else {
          $this->error('该文章所属课程不是你!',403);
        }
      } else {
        return true;
      }
    } else {
      if ($js) {
        $this->jsMsg('文章不存在!');
      } else {
        $this->error('文章不存在!',404);
      }
    }
  }

  /**
   * 初始化编辑器
   */
  public function initEditor()
  {
    Yii::app()->clientScript->registerCssFile('/public/lib/ueditor_mini1_0_0-utf8-php/themes/default/css/umeditor.min.css');
    Yii::app()->clientScript->registerScriptFile('/public/lib/ueditor_mini1_0_0-utf8-php/umeditor.config.js', CClientScript::POS_BEGIN);
    Yii::app()->clientScript->registerScriptFile('/public/lib/ueditor_mini1_0_0-utf8-php/umeditor.min.js', CClientScript::POS_BEGIN);
  }

  /**
   * 检查题库
   * @param int $bank_id
   * @param int $user_id
   * @return bool
   */
  public function checkQuestionBank($bank_id = 0, $user_id = 0)
  {
    if ($bank_id > 0) {
      $criteria = new CDbCriteria();
      $criteria->condition = 'bank_id=:bank_id';
      if ($user_id > 0) {
        $criteria->addCondition('user_id=:user_id');
        $criteria->params = array(
            ':bank_id' => $bank_id,
            ':user_id' => $user_id
        );
      } else {
        $criteria->params = array(
            ':bank_id' => $bank_id
        );
      }

      $data = QuestionBank::model()->find($criteria);
      if (empty($data)) {
        $this->jsMsg('题库不存在!');
      } else {
        return true;
      }
    } else {
      $this->jsMsg('题库不存在!');
    }
  }

  /**
   * 检测题目
   * @param int $question_id
   * @param int $user_id
   * @return bool
   */
  public function checkQuestion($question_id = 0, $user_id = 0)
  {
    if ($question_id > 0) {
      $criteria = new CDbCriteria();
      $criteria->condition = 'question_id=:question_id';
      $criteria->params = array(':question_id' => $question_id);
      if ($user_id > 0) {
        $criteria->with = array(
            'bank'
        );
      }
      $data = Question::model()->find($criteria);
      if (empty($data)) {
        $this->jsMsg('题目不存在!');
      } else if ($data->bank->user_id != $user_id) {
        $this->jsMsg('该题目所属题库不是你！');
      } else {
        return true;
      }
    } else {
      $this->jsMsg('题目不存在!');
    }
  }
}